package com.study.springsecurity.handler;

import com.study.springsecurity.constant.ErrorCode;
import com.study.springsecurity.pojo.Result;
import com.study.springsecurity.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义访问拒绝处理逻辑（当用户调用无权限访问的接口时执行）
 *
 * @Author YL
 * @Create 2024/4/3 16:20
 * @Version 1.0
 */
@Slf4j
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.error("MyAccessDeniedHandler handle error denied url={}", request.getRequestURL());
        Result result = new Result();
        result.setCode(ErrorCode.E000001.code());
        result.setMessage(accessDeniedException.getMessage());
        ResponseUtil.writeJsonUtf8(response,HttpStatus.OK,result);
    }
}
